package com.yummy.web.security.context;


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yummy.convention.lang.StringGen;

public class InMemorySessionManager implements SessionManager{
	
	private Cache<String,Session> storage;
		
	private Long timeout;
	
	public InMemorySessionManager(Long timeout){
		this.timeout = timeout;
		if(this.timeout == null || this.timeout <= 0) {
			this.timeout = default_timeout;
		}
		storage = Caffeine.newBuilder()
				.expireAfterAccess(this.timeout,default_timeunit).build();
	}

	@Override
	public void refresh(Session session) {
		storage.put(session.getId(), session);
	}

	@Override
	public Session create() {
		String sessionId = StringGen.UUID();
		AccessToken session = new AccessToken(sessionId,timeout,default_timeunit);
		refresh(session);
		return session;
	}

	@Override
	public void remove(String id) {
		storage.invalidate(id);
	}

	@Override
	public Session get(String id) {
		return storage.getIfPresent(id);
	}

	public Long getTimeout() {
		return timeout;
	}

	public void setTimeout(Long timeout) {
		this.timeout = timeout;
	}

}